package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.form.OrderListRequest;
import com.cskaoyan.order.service.OrderCoreService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter orderConverter;

    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @return void
     * @author lwq
     * @since 2022/12/04 14:28
     */
    @Override
    @Transactional
    public void cancelOrder(String orderId) {
        // 修改订单状态为取消
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
        order.setUpdateTime(new Date());
        int i = orderMapper.updateByPrimaryKeySelective(order);
        if (i != 1) {
            throw new BaseBusinessException("取消订单失败");
        }
        // 修改订单商品状态为 2库存已释放
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        i = orderItemMapper.updateStockStatus(2, orderId);
        if (i != orderItems.size()) {
            throw new BaseBusinessException("修改订单商品状态失败");
        }
        // 返还库存
        for (OrderItem orderItem : orderItems) {
            Stock stock = new Stock();
            stock.setItemId(orderItem.getItemId());
            stock.setLockCount(-orderItem.getNum());
            stock.setStockCount(orderItem.getNum().longValue());
            i = stockMapper.updateStock(stock);
            if (i != 1) {
                throw new BaseBusinessException("返还库存失败");
            }
        }
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @return void
     * @author lwq
     * @since 2022/12/04 14:55
     */
    @Override
    @Transactional
    public void deleteOrder(String orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Integer status = order.getStatus();
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        if (OrderConstants.ORDER_STATUS_INIT == status) {
            // 订单为初始化状态  删除订单需要返还库存
            for (OrderItem orderItem : orderItems) {
                // 返还商品库存
                Stock stock = new Stock();
                stock.setItemId(orderItem.getItemId());
                stock.setLockCount(-orderItem.getNum());
                stock.setStockCount(orderItem.getNum().longValue());
                int i = stockMapper.updateStock(stock);
                if (i != 1) {
                    throw new BaseBusinessException("返还库存失败");
                }
            }
        }
        // 删除订单
        int i = orderMapper.deleteByPrimaryKey(orderId);
        if (i != 1) {
            throw new BaseBusinessException("删除订单失败");
        }
        // 删除订单商品
        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        i = orderItemMapper.deleteByExample(example);
        if (i != orderItems.size()) {
            throw new BaseBusinessException("删除订单商品失败");
        }
        // 删除订单物流信息
        i = orderShippingMapper.deleteByPrimaryKey(orderId);
        if (i != 1) {
            throw new BaseBusinessException("删除订单物流信息失败");
        }
    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

    /**
     * 查询用户订单列表
     *
     * @param orderListRequest
     * @return com.cskaoyan.order.dto.OrderListResponse
     * @author lwq
     * @since 2022/12/03 16:51
     */
    @Override
    public OrderListResponse queryOrder(OrderListRequest orderListRequest) {
        PageHelper.startPage(orderListRequest.getPage(), orderListRequest.getSize());
        Example example = new Example(Order.class);
        example.setOrderByClause("create_time desc");
        example.createCriteria().andEqualTo("userId", orderListRequest.getUserId());
        // 订单
        List<Order> orders = orderMapper.selectByExample(example);
        OrderListResponse orderListResponse = new OrderListResponse();
        List<OrderDetailInfo> orderDetailInfos = new ArrayList<>();
        for (Order order : orders) {
            // 物流信息
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
            OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
            // 商品信息
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(order.getOrderId());
            List<OrderItemDto> orderItemDtos = orderConverter.items2dtos(orderItems);
            OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);
            orderDetailInfo.setOrderItemDto(orderItemDtos);
            orderDetailInfo.setOrderShippingDto(orderShippingDto);
            orderDetailInfos.add(orderDetailInfo);
        }
        orderListResponse.setData(orderDetailInfos);
        // TODO 分页
        PageInfo<Order> orderInfo = new PageInfo<>(orders);
        orderListResponse.setTotal(orderInfo.getTotal());
        return orderListResponse;
    }

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return com.cskaoyan.order.dto.OrderDetailResponse
     * @author lwq
     * @since 2022/12/04 14:04
     */
    @Override
    public OrderDetailResponse orderDetail(String orderId) {
        // 订单商品信息
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        List<OrderItemDto> orderItemDtos = orderConverter.items2dtos(orderItems);
        // 物流信息
        OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
        // 订单信息
        Order order = orderMapper.selectByPrimaryKey(orderId);
        OrderDetailResponse orderDetailResponse = orderConverter.order2res(order, orderShipping);
        orderDetailResponse.setGoodsList(orderItemDtos);
        return orderDetailResponse;
    }

}
